<template>
  <div class="view_page userList">
    <el-card class="box-card">
      <!--卡片头部-->
      <div slot="header" class="clearfix">
        <!--左侧-->
        <div class="left">
          <div class="menu-title">
            设备配置
          </div>
        </div>
        <div class="right">
          <el-button type="primary" size="small" @click="wenjian = true">
            导入设备配置信息
          </el-button>
          <el-button type="primary" size="small" @click="exportxlsx">导出
          </el-button>

        </div>
      </div>
      <!-- 卡片内容 -->
      <div>
        <!--筛选-->
        <div class="query-operate">
          <el-form class="demo-form-inline indoor-scene-buzhou-list-form"
                   :inline="true" :model="TESTFROMDATA"
                   @submit.native.prevent>
            <el-form-item label="设备类型" label-width="120px"
                          style="margin-top: 5px; margin-bottom: 5px;">
              <el-select v-model="state" clearable @change="searchList()">
                <el-option v-for="item in stateList" :key="item.id"
                           :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="设备名称" label-width="120px"
                          style="margin-top: 5px; margin-bottom: 5px;">
              <el-input clearable @clear="searchList"
                        v-model="TESTFROMDATA.title"
                        placeholder="请输入设备名称"
                        @keyup.native.enter="searchList()"></el-input>
            </el-form-item>

            <el-form-item
              style="margin-top: 5px; margin-bottom: 5px;margin-left: 10px;">
              <el-button type="primary" @click="searchList()">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-table :data="datalist" style="width: 100%" ref="myTable" id='tab2'>
          <el-table-column prop="id" label="ID" align="center" min-width="50">
          </el-table-column>
          <el-table-column prop="name" label="设备名称" align="center"
                           min-width="140">
          </el-table-column>
          <el-table-column prop="equipment_type_name" label="设备类型"
                           align="center" min-width="100">
          </el-table-column>
          <el-table-column prop="unityInfo.posX" label="气泡X轴位置"
                           align="center" min-width="100">
          </el-table-column>
          <el-table-column prop="unityInfo.posY" label="气泡Y轴位置"
                           align="center" min-width="100">
          </el-table-column>
          <el-table-column prop="unityInfo.posZ" label="气泡Z轴位置"
                           align="center" min-width="100">
          </el-table-column>
          <el-table-column prop="unityInfo.focusingX" label="聚焦气泡X值"
                           align="center" min-width="100">
          </el-table-column>
          <el-table-column prop="unityInfo.focusingY" label="聚焦气泡Y值"
                           align="center" min-width="100">
          </el-table-column>
          <el-table-column prop="unityInfo.focusingDistance"
                           label="聚焦气泡距离" align="center" min-width="100">
          </el-table-column>
          <el-table-column prop="unityInfo.remark" label="保留字段"
                           align="center" min-width="100">
          </el-table-column>
          <!--<el-table-column prop="unityInfo.thumbnailPath" label="缩略图地址" align="center" min-width="100">
                    </el-table-column>
                    <el-table-column prop="unityInfo.modelId" label="模型ID" align="center" min-width="100">
                    </el-table-column>-->
          <el-table-column fixed="right" label="操作" min-width="140"
                           align="center">
            <template slot-scope="scope">
              <div style="display: flex;align-items: center;flex-wrap: wrap; ">
                <el-button type="primary" size="small"
                           @click="navtoAdd(scope.row.id)">修改
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!--分页-->
        <pagination :total="total" :currentPage="pageNum" :pageSize="size"
                    position="right"
                    @search="searchPagination">
        </pagination>
      </div>
    </el-card>

    <!--修改弹框-->
    <el-dialog :close-on-click-modal="false" title="修改设备配置"
               :visible.sync="dialogVisible" width="35%">
      <el-form ref="form" label-width="140px">
        <el-form-item label="气泡X轴位置" :required="true">
          <el-input v-model="liveData.posX"
                    placeholder="请输入气泡X轴位置"></el-input>
        </el-form-item>
        <el-form-item label="气泡Y轴位置" :required="true">
          <el-input v-model="liveData.posY"
                    placeholder="请输入气泡Y轴位置"></el-input>
        </el-form-item>
        <el-form-item label="气泡Z轴位置" :required="true">
          <el-input v-model="liveData.posZ"
                    placeholder="请输入气泡Z轴位置"></el-input>
        </el-form-item>
        <el-form-item label="聚焦气泡X轴位置" :required="true">
          <el-input v-model="liveData.focusingX"
                    placeholder="请输入聚焦气泡X轴位置"></el-input>
        </el-form-item>
        <el-form-item label="聚焦气泡Y轴位置" :required="true">
          <el-input v-model="liveData.focusingY"
                    placeholder="请输入聚焦气泡Y轴位置"></el-input>
        </el-form-item>
        <el-form-item label="聚焦气泡距离" :required="true">
          <el-input v-model="liveData.focusingDistance"
                    placeholder="请输入聚焦气泡距离"></el-input>
        </el-form-item>
        <el-form-item label="保留字段">
          <el-input v-model="liveData.remark"
                    placeholder="请输入保留字段"></el-input>
        </el-form-item>
        <!--				<el-form-item label="缩略图地址">
                  <el-input v-model="liveData.thumbnailPath" placeholder="请输入缩略图地址"></el-input>
                </el-form-item>
                <el-form-item label="保留字段">
                  <el-input v-model="liveData.remark" placeholder="请输入保留字段"></el-input>
                </el-form-item>
                <el-form-item label="模型ID">
                  <el-input v-model="liveData.modelId" placeholder="请输入模型ID"></el-input>
                </el-form-item>-->
      </el-form>
      <span slot="footer" class="dialog-footer">
				<el-button @click="cancel">取 消</el-button>
				<el-button type="primary" @click="save">确 定</el-button>
			</span>
    </el-dialog>

    <el-dialog
      title="导入设备配置信息"
      :visible.sync="wenjian"
      width="30%"
      :before-close="handleClose"
    >
      <el-upload
        class="upload-demo"
        ref="upload"
        :action="upload"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :file-list="fileList"
        :data="uploadData"
        :before-upload="beforeAvatarUpload"
        :on-success="handleAvatarSuccess"
        :on-error="handleAvatarError"
        :auto-upload="true"
        :limit="1"
        accept=".xlsx,.xls"
      >
        <el-button slot="trigger" size="small" type="primary"
        >选择文件
        </el-button
        >
      </el-upload>
    </el-dialog>


    <el-table :data="all_datalist"
              style="width: 100%;position: absolute;top: 10000px;" ref="myTable"
              id='tab1' v-show='false'>
      <el-table-column prop="id" label="ID" align="center" min-width="50">
      </el-table-column>
      <el-table-column prop="name" label="设备名称" align="center"
                       min-width="140">
      </el-table-column>
      <!-- <el-table-column prop="equipment_type_name" label="设备类型" align="center" min-width="100">
      </el-table-column> -->
      <el-table-column prop="unityInfo.posX" label="气泡X轴位置" align="center"
                       min-width="100">
      </el-table-column>
      <el-table-column prop="unityInfo.posY" label="气泡Y轴位置" align="center"
                       min-width="100">
      </el-table-column>
      <el-table-column prop="unityInfo.posZ" label="气泡Z轴位置" align="center"
                       min-width="100">
      </el-table-column>
      <el-table-column prop="unityInfo.focusingX" label="聚焦气泡X值"
                       align="center" min-width="100">
      </el-table-column>
      <el-table-column prop="unityInfo.focusingY" label="聚焦气泡Y值"
                       align="center" min-width="100">
      </el-table-column>
      <el-table-column prop="unityInfo.focusingDistance" label="聚焦气泡距离"
                       align="center" min-width="100">
      </el-table-column>
      <el-table-column prop="unityInfo.remark" label="保留字段" align="center"
                       min-width="100">
      </el-table-column>
      <!--<el-table-column prop="unityInfo.thumbnailPath" label="缩略图地址" align="center" min-width="100">
      </el-table-column>
      <el-table-column prop="unityInfo.modelId" label="模型ID" align="center" min-width="100">
      </el-table-column>-->
      <!-- <el-table-column fixed="right" label="操作" min-width="140" align="center">
        <template slot-scope="scope">
          <div style="display: flex;align-items: center;flex-wrap: wrap; ">
            <el-button type="primary" size="small" @click="navtoAdd(scope.row.id)">修改
            </el-button>
          </div>
        </template>
      </el-table-column> -->
    </el-table>


  </div>
</template>

<script>
import {
  Message
} from "element-ui";
import pagination from "@/components/common/pagination/pagination";
// 导入excel依赖
import FileSaver from "file-saver";
import XLSX from "xlsx";

export default {
  components: {
    pagination
  },
  watch: {
    total: {
      handler(newVal, oldVal) {
        let _this = this;
        _this.total = newVal || 0;
        console.log("监听total：", _this.total);
        if (_this.total <= 0) {
          return;
        }
        var datas = {
          page: 1,
          size: _this.total
        };
        _this.$apis.equipment_list(datas).then(res => {
          if (res.result == 0) {
            _this.all_datalist = res.data;
          }
        });
      },
      immediate: true,
      deep: true
    }
  },
  data() {
    return {
      // 筛选内容
      TESTFROMDATA: {
        title: ""
      },
      // 状态
      state: -1,
      stateList: [{
        id: -1,
        name: "全部"
      }],

      //富文本文档类型
      liveData: {
        posX: "",
        posY: "",
        posZ: "",
        focusingX: "",
        focusingY: "",
        focusingDistance: "",
        thumbnailPath: "",
        remark: "",
        modelId: ""
      },

      // 弹窗
      dialogVisible: false,
      itemID: "", //记录选中的id

      // 列表的数据
      datalist: [],
      pageNum: 1,
      page: 1,
      size: 10,
      total: 0,
      all_datalist: [],
      wenjian: false,
      uploadUrl: this.$apis.getUploadUrl() + "/file/upload", //上传地址
      upload: this.$apis.getUploadUrl() + "/unityInfo/import", //上传地址
      uploadData: {
        // id: JSON.parse(
        //   localStorage.getItem(
        //     this.$apis.getLocalKey().loginPersonnelInformation
        //   )
        // ).data.id //没用
        type: 4

      },
      fileList: [],
      file: {},

    };
  },
  created() {
    // this.getstateList();
    // this.getListPage();
    console.log('~~~~~~~~~~~~~~')
  },
  mounted() {
  },
  methods: {
    initData() {
      this.liveData = {
        posX: "",
        posY: "",
        posZ: "",
        focusingX: "",
        focusingY: "",
        focusingDistance: "",
        thumbnailPath: "",
        remark: "",
        modelId: ""
      };
    },
    is_state(item) {
      //  state 0 正常 1 异常 2 故障
      if (item == 0) {
        return "正常";
      } else if (item == 1) {
        return "异常";
      } else if (item == 2) {
        return "故障";
      }
    },
    //河流类型
    approvalstate(item) {
      switch (item) {
        case 1:
          return "河流";
          break;
        case 2:
          return "水库";
          break;
        case 3:
          return "坑塘";
          break;
        default:
          break;
      }
    },
    addressData(item) {
      // console.log("item:", item);
      // if (item != null || item != "") {
      //   var data = JSON.parse(item);
      //   return data;
      // } else {
      //   return "123";
      // }
      if (item == null || item == "") {
        return "";
      } else {
        var data = JSON.parse(item);
        return data.poiname;
      }
    },
    //切换状态
    changetype() {
      var _this = this;
      _this.page = 1;
      _this.getListPage();
    },
    getstateList() {
      var _this = this;
      var datas = {
        page: _this.page,
        size: 999
      };
      _this.$apis.equipment_type_list(datas).then(res => {
        if (res.result == 0) {
          // _this.stateList = [];
          _this.stateList = [{
            id: -1,
            name: "全部"
          }];
          for (let i = 0; i < res.data.length; i++) {
            _this.stateList.push(res.data[i]);
          }
          _this.getListPage();
        }
      });
    },
    //查询列表
    getListPage() {
      var _this = this;
      var datas = {
        equipment_type: this.state,
        name: _this.TESTFROMDATA.title,
        page: _this.page,
        size: _this.size
      };
      _this.$apis.equipment_list(datas).then(res => {
        if (res.result == 0) {
          _this.datalist = res.data;
          _this.total = res.rows;
          _this.pageNum = res.page;
        }
      });
    },
    //模糊查询
    searchList() {
      this.page = 1;
      this.datalist = [];
      this.getListPage();
    },
    //分页
    searchPagination(page) {
      this.page = page;
      localStorage.setItem("page", page);
      this.getListPage();
    },
    //新增
    navtoAdd(selfID) {
      var _this = this;
      this.initData();

      var datas = {
        id: selfID
      };
      // 查询详情
      _this.$apis.equipment_query(datas).then(res => {
        if (res.result == 0) {
          _this.liveData = res.data.unityInfo;
          _this.itemID = _this.liveData.id;
          console.log("_this.liveData:", _this.liveData);
          _this.dialogVisible = true;
        }
      });
    },
    //取消
    cancel() {
      this.dialogVisible = false;
    },
    save() {
      var _this = this;
      var datas = _this.liveData;
      datas.id = _this.itemID;
      console.log("save-datas:", datas);
      var reg = /(https?|ftp|file):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/;
      if (datas.posX == "") {
        Message.error("气泡X轴位置不能为空");
        return;
      }
      if (datas.posY == "") {
        Message.error("气泡Y轴位置不能为空");
        return;
      }
      if (datas.posZ == "") {
        Message.error("气泡Z轴位置不能为空");
        return;
      }
      if (datas.focusingX == "") {
        Message.error("聚焦气泡X轴位置不能为空");
        return;
      }
      if (datas.focusingY == "") {
        Message.error("聚焦气泡Y轴位置不能为空");
        return;
      }
      if (datas.focusingDistance == "") {
        Message.error("聚焦气泡距离不能为空");
        return;
      }
      // if (datas.thumbnailPath == "") {
      //   Message.error("缩略图地址不能为空");
      //   return;
      // }
      if (datas.thumbnailPath != "") {
        if (!reg.test(datas.thumbnailPath)) {
          Message.error("请填写正确格式的缩略图地址");
          return;
        }
      }
      // if (datas.remark == "") {
      //   Message.error("保留字段不能为空");
      //   return;
      // }
      _this.$apis.unityInfo_update(datas).then(res => {
        if (res.result == 0) {
          Message.success("修改成功");
          this.dialogVisible = false;
          this.getListPage();
        }
      });
    },
    // //导出表格
    // exportxlsx() {
    // 	var xx = JSON.parse(JSON.stringify(this.all_datalist));
    // 	// console.log(xx)
    // 	for (let i in xx) {
    // 		xx[i].posX = xx[i].unityInfo.posX
    // 		xx[i].posY = xx[i].unityInfo.posY
    // 		xx[i].posZ = xx[i].unityInfo.posZ
    // 		xx[i].focusingX = xx[i].unityInfo.focusingX
    // 		xx[i].focusingY = xx[i].unityInfo.focusingY
    // 		xx[i].focusingDistance = xx[i].unityInfo.focusingDistance
    // 		xx[i].thumbnailPath = xx[i].unityInfo.thumbnailPath
    // 		xx[i].remark = xx[i].unityInfo.remark
    // 		xx[i].modelId = xx[i].unityInfo.modelId

    // 		// xx[i].imei_number = ''+xx[i].imei_number
    // 	}
    // 	var column = [];
    // 	this.$refs["myTable"].$children.forEach(element => {
    // 		if (element.label && element.label != "操作") {
    // 			let temp = {

    // 			};
    // 			switch (element.label) {
    // 				case '气泡X轴位置':
    // 					 temp = {
    // 						title: element.label,
    // 						key: 'posX', //key值对应表单数据字段名称
    // 						type: "text"
    // 					};
    // 					break;
    // 					case '设备类型':
    // 						 return;
    // 						break;
    // 				case '气泡Y轴位置':
    // 					 temp = {
    // 						title: element.label,
    // 						key: 'posY', //key值对应表单数据字段名称
    // 						type: "text"
    // 					};
    // 					break;
    // 				case '气泡Z轴位置':
    // 					 temp = {
    // 						title: element.label,
    // 						key: 'posZ', //key值对应表单数据字段名称
    // 						type: "text"
    // 					};
    // 					break;
    // 				case '聚焦气泡X值':
    // 					 temp = {
    // 						title: element.label,
    // 						key: 'focusingX', //key值对应表单数据字段名称
    // 						type: "text"
    // 					};
    // 					break;
    // 				case '聚焦气泡Y值':
    // 					 temp = {
    // 						title: element.label,
    // 						key: 'focusingY', //key值对应表单数据字段名称
    // 						type: "text"
    // 					};
    // 					break;
    // 				case '聚焦气泡距离':
    // 					 temp = {
    // 						title: element.label,
    // 						key: 'focusingDistance', //key值对应表单数据字段名称
    // 						type: "text"
    // 					};
    // 					break;
    // 				case '缩略图地址':
    // 					 temp = {
    // 						title: element.label,
    // 						key: 'thumbnailPath', //key值对应表单数据字段名称
    // 						type: "text"
    // 					};
    // 					break;
    // 				case '保留字段':
    // 					 temp = {
    // 						title: element.label,
    // 						key: 'remark', //key值对应表单数据字段名称
    // 						type: "text"
    // 					};
    // 					break;
    // 				case '模型ID':
    // 					 temp = {
    // 						title: element.label,
    // 						key: 'modelId', //key值对应表单数据字段名称
    // 						type: "text"
    // 					};
    // 					break;
    // 				default:
    // 				 temp = {
    // 					title: element.label,
    // 					key: element.prop, //key值对应表单数据字段名称
    // 					type: "text"
    // 				};
    // 					break;
    // 			}


    // 			column.push(temp);
    // 		}
    // 	});
    // 	var datas = xx; //表单数据
    // 	console.log(column)
    // 	const excelName = "设备配置_" + new Date().toLocaleString()+'.xlsx'; //文件名称
    // 	// console.log(column, datas, excelName)
    // 	// table2excel(column, datas, excelName);
    // 	this.$table2excel(column, datas, excelName);
    // },
    // 定义导出表格触发事件
    exportxlsx() {

      // const tt = document.querySelector('#tab2')

      // const dd = tt.cloneNode(true);
      //  dd.setAttribute('id', 'tab1');
      // console.log(dd)
      const wb = XLSX.utils.table_to_book(document.querySelector('#tab1'), {
        raw: true // 如果表格里有数字、日期这些、需要加上raw: true
      });
      /* 获取二进制字符串作为输出 */
      var wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array'
      });
      // console.log(wbout)
      try {
        FileSaver.saveAs(
          // Blob 对象表示一个不可变、原始数据的类文件对象
          new Blob([wbout], {type: 'application/octet-stream'}),
          // 设置导出文件名称
          "设备配置信息.xlsx"
        );
      } catch (e) {
        if (typeof console !== 'undefined') console.log(e, wbout);
      }
      return wbout;
    },

    handleClose() {
      var _this = this;
      _this.wenjian = false;
      _this.fileList = [];
    },
    //上传文件
    submitUpload() {
      // if (JSON.stringify(this.fileList)=='[]') {
      //   Message.warning('请上传图片')
      //   return
      // }
      // var _this = this
      // var datas ={
      // 	id:_this.userInfo_id,
      // 	file:_this.file
      // }

      // _this.$apis.plan_management_import(datas).then(res=>{
      // 	if(res.result==0){

      // 	}
      // })
      this.$refs.upload.submit();
    },
    //文件列表移除文件时的钩子
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    //点击文件列表中已上传的文件时的钩子
    handlePreview(file) {
      console.log(file);
    },
    //文件上传成功的钩子
    handleAvatarSuccess(res, file) {
      console.log(res, 1);
      this.errorlist = res.data;
      // var datas ={
      // 	id:this.userInfo_id,
      // 	file:res.data.url
      // }

      // _this.$apis.plan_management_import(datas).then(res=>{
      // 	if(res.result==0){

      // 	}
      // })
      if (res.result == 0) {
        // Message.success('导入成功')
        if (res.data.fail == 0) {
          Message.success(res.data.success + "条数据导入成功");
        } else {
          let line = res.data.fail_array.join(",");
          Message.error(
            "数据导入有" + res.data.fail + "条错误，在" + line + "行数据有误！"
          );
        }
      } else {
        Message.error(res.msg);
      }
      this.getListPage();
      this.handleClose();
    },
    errorClose() {
      this.errortable = false;
      this.errList = [];
    },
    //文件上传失败时的钩子
    handleAvatarError(err, file) {
      Message.error("文件上传失败，请稍后再试");
      this.wenjian = false;
    },
    //上传文件之前的钩子
    beforeAvatarUpload(file) {
      console.log(file);
      this.file = file;
      var typeList = [
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "application/vnd.ms-excel"
      ];
      // const isJPG = file.type === 'image/jpeg'
      const isJPG = typeList.includes(file.type);
      if (!isJPG) {
        Message.error("文件上传格式不对");
      }
      return isJPG;
    },

  }
};
</script>

<style>
.el-table .cell {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: normal !important;
}
</style>
